package com.chalk.common.plugins.fastdfs;

import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.exception.FdfsUnsupportStorePathException;
import com.github.tobato.fastdfs.proto.storage.DownloadByteArray;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;

/**
 * ClassName: FastDFSClient
 *
 * @author L.G
 * @Description FastDFS 客户端工具
 * @email lg10000@126.com
 * @date 2018年9月26日 上午10:34:59
 */
@Component
public class FastDFSClient {

    private static final Logger LOGGER = LoggerFactory.getLogger(FastDFSClient.class);

    @Autowired
    private FastFileStorageClient fastFileStorageClient;

    /**
     * 上传文件
     *
     * @param file 文件对象
     * @return 文件访问地址
     * @throws IOException
     */
    public synchronized String uploadFile(MultipartFile file) throws IOException {
        StorePath storePath = fastFileStorageClient.uploadFile(file.getInputStream(), file.getSize(),
                FilenameUtils.getExtension(file.getOriginalFilename()), null);
        return getResAccessUrl(storePath);
    }

    /**
     * 将一段字符串生成一个文件上传
     *
     * @param content       文件内容
     * @param fileExtension
     * @return
     */
    public synchronized String uploadFile(String content, String fileExtension) {
        byte[] buff = content.getBytes(Charset.forName("UTF-8"));
        ByteArrayInputStream stream = new ByteArrayInputStream(buff);
        StorePath storePath = fastFileStorageClient.uploadFile(stream, buff.length, fileExtension, null);
        return getResAccessUrl(storePath);
    }

    /**
     * 封装图片完整URL地址
     *
     * @param storePath
     * @return
     */
    private String getResAccessUrl(StorePath storePath) {
        String fileUrl = storePath.getFullPath();
        return fileUrl;
    }

    /**
     * 传图片并同时生成一个缩略图 "JPG", "JPEG", "PNG", "GIF", "BMP", "WBMP"
     *
     * @param file 文件对象
     * @return 文件访问地址
     * @throws IOException
     */
    public synchronized String uploadImageAndCrtThumbImage(MultipartFile file) throws IOException {
        StorePath storePath = fastFileStorageClient.uploadImageAndCrtThumbImage(file.getInputStream(), file.getSize(),
                FilenameUtils.getExtension(file.getOriginalFilename()), null);
        return getResAccessUrl(storePath);
    }

    /**
     * 获取文件
     *
     * @param fileUrl 文件访问地址
     * @return byte[]
     */
    public synchronized byte[] getFile(String fileUrl) {
        byte[] bs = new byte[]{};
        if (StringUtils.isEmpty(fileUrl)) {
            return bs;
        }
        try {
            DownloadByteArray byteArray = new DownloadByteArray();
            StorePath storePath = StorePath.praseFromUrl(fileUrl);
            bs = fastFileStorageClient.downloadFile(storePath.getGroup(), storePath.getPath(), byteArray);
        } catch (FdfsUnsupportStorePathException e) {
            LOGGER.error("获取文件异常:" + ExceptionUtils.getStackTrace(e));
        }
        return bs;
    }

    /**
     * 删除文件
     *
     * @param fileUrl 文件访问地址
     * @return
     */
    public synchronized void deleteFile(String fileUrl) {
        if (StringUtils.isEmpty(fileUrl)) {
            return;
        }
        try {
            StorePath storePath = StorePath.praseFromUrl(fileUrl);
            fastFileStorageClient.deleteFile(storePath.getGroup(), storePath.getPath());
        } catch (FdfsUnsupportStorePathException e) {
            LOGGER.error("删除文件异常:" + ExceptionUtils.getStackTrace(e));
        }
    }

    /**
     * 上传二进制流文件
     * @param inputStream
     * @param fileSize
     * @return
     * @throws IOException
     */
    public synchronized String uploadStream(InputStream inputStream, long fileSize, String originalFilename) throws IOException {
        StorePath storePath = fastFileStorageClient.uploadFile(inputStream, fileSize,
                FilenameUtils.getExtension(originalFilename), null);
        return getResAccessUrl(storePath);
    }

}
